<?php
    /**
     * 交易管理
     *
     *
     *
     */

    defined('IN_NWIDC') or exit('Access Invalid!');

    class proxy_orderControl extends SystemControl {
        /**
         * 每次导出订单数量
         *
         * @var int
         */
        const EXPORT_SIZE = 1000;

        public function __construct() {
            parent::__construct();
            Language::read('trade');
        }

        public function indexOp() {
            $model_order = Model('order');
            $condition = array();
            if ($_GET['order_sn']) {
                $condition['order_sn'] = $_GET['order_sn'];
            }
            if ($_GET['store_name']) {
                $condition['store_name'] = $_GET['store_name'];
            }
            // if(in_array($_GET['order_state'],array('0','10','20','30','40'))){
            // 	$condition['order_state'] = $_GET['order_state'];
            // }
            $condition['order_state'] = 40;
            if ($_GET['payment_code']) {
                $condition['payment_code'] = $_GET['payment_code'];
            }
            if ($_GET['buyer_name']) {
                $condition['buyer_name'] = $_GET['buyer_name'];
            }


            $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $_GET['query_start_time']);
            $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $_GET['query_end_time']);
            $start_unixtime = $if_start_time ? strtotime($_GET['query_start_time']) : null;
            $end_unixtime = $if_end_time ? strtotime($_GET['query_end_time']) : null;
            if ($start_unixtime || $end_unixtime) {
                $condition['add_time'] = array(
                    'time',
                    array(
                        $start_unixtime,
                        $end_unixtime
                    )
                );
            }
            $order_list = $model_order->getOrderList($condition, 30);

            foreach ($order_list as $order_id => $order_info) {
                //显示取消订单
                $order_list[$order_id]['if_cancel'] = $model_order->getOrderOperateState('system_cancel', $order_info);
                //显示收到货款
                $order_list[$order_id]['if_system_receive_pay'] = $model_order->getOrderOperateState('system_receive_pay', $order_info);
            }
            //显示支付接口列表(搜索)
            $payment_list = Model('payment')->getPaymentOpenList();
            Tpl::output('payment_list', $payment_list);

            Tpl::output('order_list', $order_list);
            Tpl::output('show_page', $model_order->showpage());
            Tpl::showpage('proxy.order.index');
        }

        function add_taskOp() {
            $m = Model();
            $stime = strtotime($_POST['stime']);
            $etime = strtotime($_POST['etime']);
            if ($stime > $etime) {
                exit('结束时间不能小于起止时间！');
            }
            $data = array(
                'start_time' => $stime,
                'end_time'   => $etime,
                'money'      => $_POST['money'],
                'member_id'  => $_POST['mid']
            );
            $m->table('proxy_task')->insert($data);
            exit('添加成功！');
        }

        function delete_taskOp() {
            $m = Model();
            $id = $_POST['id'];
            if (
            $m->table('proxy_task')->where(array('id' => $id))->delete()
            ) {
                exit('删除成功！');
            }
        }

        /**
         * 平台订单状态操作
         *
         */
        public function change_stateOp() {
            $order_id = intval($_GET['order_id']);
            if ($order_id <= 0) {
                showMessage(L('miss_order_number'), $_POST['ref_url'], 'html', 'error');
            }
            $model_order = Model('order');

            //获取订单详细
            $condition = array();
            $condition['order_id'] = $order_id;
            $order_info = $model_order->getOrderInfo($condition);

            if ($_GET['state_type'] == 'cancel') {
                $result = $this->_order_cancel($order_info);
            } elseif ($_GET['state_type'] == 'receive_pay') {
                $result = $this->_order_receive_pay($order_info, $_POST);
            }
            if (!$result['state']) {
                showMessage($result['msg'], $_POST['ref_url'], 'html', 'error');
            } else {
                showMessage($result['msg'], $_POST['ref_url']);
            }
        }

        /**
         * 系统取消订单
         */
        private function _order_cancel($order_info) {
            $order_id = $order_info['order_id'];
            $model_order = Model('order');
            $logic_order = Logic('order');
            $if_allow = $model_order->getOrderOperateState('system_cancel', $order_info);
            if (!$if_allow) {
                return callback(false, '无权操作');
            }
            $result = $logic_order->changeOrderStateCancel($order_info, 'system', $this->admin_info['name']);
            if ($result['state']) {
                $this->log(L('order_log_cancel') . ',' . L('order_number') . ':' . $order_info['order_sn'], 1);
            }
            return $result;
        }

        /**
         * 系统收到货款
         *
         * @throws Exception
         */
        private function _order_receive_pay($order_info, $post) {
            $order_id = $order_info['order_id'];
            $model_order = Model('order');
            $logic_order = Logic('order');
            $if_allow = $model_order->getOrderOperateState('system_receive_pay', $order_info);
            if (!$if_allow) {
                return callback(false, '无权操作');
            }

            if (!chksubmit()) {
                Tpl::output('order_info', $order_info);
                //显示支付接口列表
                $payment_list = Model('payment')->getPaymentOpenList();
                //去掉预存款和货到付款
                foreach ($payment_list as $key => $value) {
                    if ($value['payment_code'] == 'predeposit' || $value['payment_code'] == 'offline') {
                        unset($payment_list[$key]);
                    }
                }
                Tpl::output('payment_list', $payment_list);
                Tpl::showpage('order.receive_pay');
                exit();
            }
            $order_list = $model_order->getOrderList(array(
                'pay_sn'      => $order_info['pay_sn'],
                'order_state' => ORDER_STATE_NEW
            ));
            $result = $logic_order->changeOrderReceivePay($order_list, 'system', $this->admin_info['name'], $post);
            if ($result['state']) {
                $this->log('将订单改为已收款状态,' . L('order_number') . ':' . $order_info['order_sn'], 1);
            }
            return $result;
        }

        /**
         * 查看订单
         *
         */
        public function show_orderOp() {
            $order_id = intval($_GET['order_id']);
            if ($order_id <= 0) {
                showMessage(L('miss_order_number'));
            }
            $model_order = Model('order');
            $order_info = $model_order->getOrderInfo(array('order_id' => $order_id), array(
                'order_goods',
                'order_common',
                'store'
            ));

            //订单变更日志
            $log_list = $model_order->getOrderLogList(array('order_id' => $order_info['order_id']));
            Tpl::output('order_log', $log_list);

            //退款退货信息
            $model_refund = Model('refund_return');
            $condition = array();
            $condition['order_id'] = $order_info['order_id'];
            $condition['seller_state'] = 2;
            $condition['admin_time'] = array(
                'gt',
                0
            );
            $return_list = $model_refund->getReturnList($condition);
            Tpl::output('return_list', $return_list);

            //退款信息
            $refund_list = $model_refund->getRefundList($condition);
            Tpl::output('refund_list', $refund_list);

            //卖家发货信息
            if (!empty($order_info['extend_order_common']['daddress_id'])) {
                $daddress_info = Model('daddress')->getAddressInfo(array('address_id' => $order_info['extend_order_common']['daddress_id']));
                Tpl::output('daddress_info', $daddress_info);
            }

            Tpl::output('order_info', $order_info);
            Tpl::showpage('order.view');
        }

        /**
         * 导出
         *
         */
        public function export_step1Op() {
            $lang = Language::getLangContent();

            $model_order = Model('order');
            $condition = array();
            if ($_GET['order_sn']) {
                $condition['order_sn'] = $_GET['order_sn'];
            }
            if ($_GET['store_name']) {
                $condition['store_name'] = $_GET['store_name'];
            }
            if (in_array($_GET['order_state'], array(
                '0',
                '10',
                '20',
                '30',
                '40'
            ))) {
                $condition['order_state'] = $_GET['order_state'];
            }
            if ($_GET['payment_code']) {
                $condition['payment_code'] = $_GET['payment_code'];
            }
            if ($_GET['buyer_name']) {
                $condition['buyer_name'] = $_GET['buyer_name'];
            }
            $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $_GET['query_start_time']);
            $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $_GET['query_end_time']);
            $start_unixtime = $if_start_time ? strtotime($_GET['query_start_time']) : null;
            $end_unixtime = $if_end_time ? strtotime($_GET['query_end_time']) : null;
            if ($start_unixtime || $end_unixtime) {
                $condition['add_time'] = array(
                    'time',
                    array(
                        $start_unixtime,
                        $end_unixtime
                    )
                );
            }

            if (!is_numeric($_GET['curpage'])) {
                $count = $model_order->getOrderCount($condition);
                $array = array();
                if ($count > self::EXPORT_SIZE) {    //显示下载链接
                    $page = ceil($count / self::EXPORT_SIZE);
                    for ($i = 1; $i <= $page; $i++) {
                        $limit1 = ($i - 1) * self::EXPORT_SIZE + 1;
                        $limit2 = $i * self::EXPORT_SIZE > $count ? $count : $i * self::EXPORT_SIZE;
                        $array[$i] = $limit1 . ' ~ ' . $limit2;
                    }
                    Tpl::output('list', $array);
                    Tpl::output('murl', 'index.php?act=order&op=index');
                    Tpl::showpage('export.excel');
                } else {    //如果数量小，直接下载
                    $data = $model_order->getOrderList($condition, '', '*', 'order_id desc', self::EXPORT_SIZE);
                    $this->createExcel($data);
                }
            } else {    //下载
                $limit1 = ($_GET['curpage'] - 1) * self::EXPORT_SIZE;
                $limit2 = self::EXPORT_SIZE;
                $data = $model_order->getOrderList($condition, '', '*', 'order_id desc', "{$limit1},{$limit2}");
                $this->createExcel($data);
            }
        }

        /**
         * 生成excel
         *
         * @param array $data
         */
        private function createExcel($data = array()) {
            Language::read('export');
            import('libraries.excel');
            $excel_obj = new Excel();
            $excel_data = array();
            //设置样式
            $excel_obj->setStyle(array(
                'id'   => 's_title',
                'Font' => array(
                    'FontName' => '宋体',
                    'Size'     => '12',
                    'Bold'     => '1'
                )
            ));
            //header
            $excel_data[0][] = array(
                'styleid' => 's_title',
                'data'    => L('exp_od_no')
            );
            $excel_data[0][] = array(
                'styleid' => 's_title',
                'data'    => L('exp_od_store')
            );
            $excel_data[0][] = array(
                'styleid' => 's_title',
                'data'    => L('exp_od_buyer')
            );
            $excel_data[0][] = array(
                'styleid' => 's_title',
                'data'    => L('exp_od_xtimd')
            );
            $excel_data[0][] = array(
                'styleid' => 's_title',
                'data'    => L('exp_od_count')
            );
            $excel_data[0][] = array(
                'styleid' => 's_title',
                'data'    => L('exp_od_yfei')
            );
            $excel_data[0][] = array(
                'styleid' => 's_title',
                'data'    => L('exp_od_paytype')
            );
            $excel_data[0][] = array(
                'styleid' => 's_title',
                'data'    => L('exp_od_state')
            );
            $excel_data[0][] = array(
                'styleid' => 's_title',
                'data'    => L('exp_od_storeid')
            );
            $excel_data[0][] = array(
                'styleid' => 's_title',
                'data'    => L('exp_od_buyerid')
            );
            $excel_data[0][] = array(
                'styleid' => 's_title',
                'data'    => L('exp_od_bemail')
            );
            //data
            foreach ((array)$data as $k => $v) {
                $tmp = array();
                $tmp[] = array('data' => 'NC' . $v['order_sn']);
                $tmp[] = array('data' => $v['store_name']);
                $tmp[] = array('data' => $v['buyer_name']);
                $tmp[] = array('data' => date('Y-m-d H:i:s', $v['add_time']));
                $tmp[] = array(
                    'format' => 'Number',
                    'data'   => ncPriceFormat($v['order_amount'])
                );
                $tmp[] = array(
                    'format' => 'Number',
                    'data'   => ncPriceFormat($v['shipping_fee'])
                );
                $tmp[] = array('data' => orderPaymentName($v['payment_code']));
                $tmp[] = array('data' => orderState($v));
                $tmp[] = array('data' => $v['store_id']);
                $tmp[] = array('data' => $v['buyer_id']);
                $tmp[] = array('data' => $v['buyer_email']);
                $excel_data[] = $tmp;
            }
            $excel_data = $excel_obj->charset($excel_data, CHARSET);
            $excel_obj->addArray($excel_data);
            $excel_obj->addWorksheet($excel_obj->charset(L('exp_od_order'), CHARSET));
            $excel_obj->generateXML($excel_obj->charset(L('exp_od_order'), CHARSET) . $_GET['curpage'] . '-' . date('Y-m-d-H', time()));
        }


        public function we_distributeOp() {
            Tpl::showpage("proxy.order.we_distribute");
        }

        public function we_distribute_memberOp() {
            Tpl::showpage("proxy.order.we_distribute_member");
        }

        public function we_distribute_applyOp() {
            Tpl::showpage("proxy.order.we_distribute_apply");
        }

        function point_parent_proxyOp() {
            $member = ml('member')->where(['member_name' => trim($_GET['member_name'])])->find();
            if (!$member) {
                echo 'failed';
                exit;
            }
            $dis = new Distribute($member['member_id']);
            //不是分销商
            if (!$dis->getMinfo()) {
                echo 'failed';
                exit;
            }
            //是买家
            if ($dis->isBuyer()) {
                echo 'failed';
                exit;
            }


            $child = new Distribute($_GET['member_id']);
            if ($child->isBuyer()) {
                //如果是买家，可以直接指派
                ml('proxy')->where(['member_id' => $child->getMemberId()])->update([
                    'parent_id' => $dis->getMemberId()
                ]);
            }
            else{
                if ($child->getLevel() <= $dis->getLevel()) {
                    echo 'falied';
                    exit;
                }
                else{
                    ml('proxy')->where(['member_id' => $child->getMemberId()])->update([
                        'parent_id' => $dis->getMemberId()
                    ]);
                }
            }

            echo 'success';

        }

        function proxy_sel_memberOp() {
            Tpl::showpage('proxy_sel_member');
        }

        function give_memberOp() {
            $parent = $_GET['parent'];
            $id = $_GET['id'];
            $pinfo = ml('proxy')->find($parent);
            if (!$pinfo || $pinfo['is_buyer'] == 1) {
                echo "上级会员不是分销商";
                exit;
            }
            $cinfo = ml('proxy')->find($id);
            /**
             * 如果是普通会员
             */
            if (!$cinfo) {
                $dis = new Distribute($parent);
                $dis->addBuyer($id);
                echo "添加成功";
                exit;
            }

            else if($cinfo['is_buyer'] == 1){

                ml('proxy')->where(['member_id' => $id])->update([
                    'parent_id' => $parent
                ]);
                echo "添加成功";
                exit;
            }
            /**
             * 如果是分销商，那么层级必须小于父级
             */
            else if ($cinfo['is_buyer'] == 0) {
                $pdis = new Distribute($parent);
                $cdis = new Distribute($id);
                if ($cdis->getLevel() >= $pdis->getLevel()) {
                    echo "层级错误，添加失败";
                    exit;
                }
                ml('proxy')->where(['member_id' => $id])->update([
                    'parent_id' => $parent
                ]);
                echo "添加成功";
                exit;
            }



        }

        public function cancel_distributeOp() {
            $id = $_GET['member_id'];
            do {
                if (!ml('proxy')->find($id)) {
                    break;
                }
                $dis = new Distribute($id);
                $dis->cancelPermission();

            } while (0);
            echo "<script>alert('操作成功');history.go(-1);</script>";
        }

        public function acceptOp() {
            $id = $_GET['id'];
            if (emptY($id)) {
                echo 'failed';
                exit;
            }
            $info = ml('proxy_apply')->find($id);
            if (!$info) {
                echo 'failed';
                exit;
            }
            if ($info['proxy_member_id'] != 0) {
                echo 'failed';
                exit;
            }
            $data = array(
                'member_id' => $info['member_id'],
                'parent_id' => 0,
                'infomation' => '',
                'price_formula' => '',
                'is_buyer' => 0
            );
            Model()->table('proxy')->insert($data,true);
            ml('proxy_apply')->where(['id' => $id])->update([
                'status' => 'state_success'
            ]);
            echo 'success';
        }

        public function rejectOp() {
            $id = $_GET['id'];
            if (emptY($id)) {
                echo 'failed';
                exit;
            }
            $info = ml('proxy_apply')->find($id);
            if (!$info) {
                echo 'failed';
                exit;
            }
            ml('proxy_apply')->where(['id' => $id])->update([
                'status' => 'state_cancel'
            ]);
            echo 'success';
        }

	    public function change_is_specialOp() {
		    Model()->table("proxy")->where(['member_id' => $_GET['member_id']])->update([
			    'is_special' => $_GET['value']
		    ]);
	    }

	    public function change_inviterOp() {
		    $smember = ml('member')->find($_GET['id']);
		    $member = ml('member')->find([
			    'member_id' => $_GET['username'],
		    ]);
		    if (!$member) {
			    return;
		    }
		    $dis = new Distribute($member['member_id']);
		    if ($dis->isBuyer()) {
			    return;
		    }
		    if (empty($member['wechat_openid'])) {
			    return;
		    }
		    ml('proxy_pre')->insert([
		    	'openid' => $smember['wechat_openid'],
			    'parent_id' => $member['member_id'],
		    ],true);
		    echo 'success';
	    }
    }
